﻿using System.Web.Mvc;

namespace Sidvall.Web.Security
{
	[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments"), System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
	public sealed class AuthenticationMethodAuthorizeAttribute : AuthorizeAttribute
	{
		#region Public Members

		#region AuthorizeCore

		protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
		{
			if (httpContext == null)
				throw new System.ArgumentNullException("httpContext");
			if (httpContext.Request == null)
				return false;
			if (httpContext.User == null)
				return false;
			if (!httpContext.User.Identity.IsAuthenticated)
				return false;
			return this.Validator.IsValid(httpContext.User.Identity, httpContext.Request.Form);
		}

		#endregion

		#endregion
		#region Private Members

		private AuthenticationMethodValidator Validator { get; set; }

		#endregion
		#region Constructors

		public AuthenticationMethodAuthorizeAttribute()
			: this(null, null)
		{
			this.Validator = new AuthenticationMethodValidator()
			{
				AuthenticationMethod = null,
			};
		}
		public AuthenticationMethodAuthorizeAttribute(string authenticationMethod)
			: this(authenticationMethod, null)
		{
		}
		public AuthenticationMethodAuthorizeAttribute(string authenticationMethod, string ignoredUsers)
		{
			this.Validator = new AuthenticationMethodValidator()
			{
				AuthenticationMethod = authenticationMethod,
			};
			if (!string.IsNullOrWhiteSpace(ignoredUsers))
			{
				var users = ignoredUsers.Split(new string[] { "," }, System.StringSplitOptions.RemoveEmptyEntries);
				foreach (var user in users)
					this.Validator.IgnoredUsers.Add(user);
			}
		}

		#endregion
	}
}
